<!--
 * @Author: 赵宇
 * @Description: 
 * @Date: 2023-04-17 10:54:15
 * @LastEditTime: 2023-04-26 17:47:09
 * @LastEditors: pancc 527847805@qq.com
 * @FilePath: \pcj\src\page\order\orderBuyEdit.vue
-->
<template>
  <div class="orderBuyEdit">
    <ul class="header-buttons">
      <li>
        <z-button icon="fanhui" type="" link title="返回" @click="onBack" />
        <z-button title="刷新" icon="refresh" color="#40485b" @click="onRefresh" />
        <z-button v-if="formOrderBuy.statusId === 1" @click="onEdit">编辑</z-button>
        <z-button v-if="[0, 1].includes(formOrderBuy.statusId)" @click="onSave">保存</z-button>
        <z-button v-if="formOrderBuy.statusId === 1" @click="onSubmit">提交</z-button>
        <z-button v-if="formOrderBuy.statusId === 5" @click="onDreaf">重置草稿</z-button>
      </li>
      <li class="dis-flex">
        <columnSetting v-model="columns.buy" name="orderBuyEdit/GetModel" />
      </li>
    </ul>
    <!-- 头部基础信息  -->
    <buyForm :disabled="!status.isEdit" v-model:column="buyFormColumn" ref="buyFormRef" />
    <!-- 头部自定义规格 -->
    <spec :disabled="!status.isEdit" isArray v-model:data="status.customObjectValues" ref="specRef" />
    <!-- 产品明细 -->
    <buyTable v-model="formOrderBuy.orderBuyProducts" :isTax="isTax" :disabled="!status.isEdit"
      v-model:column="columns.buyDetail" ref="buyTableRef">
    </buyTable>

    <ul class="flow-page-header">
      <li>其他费用</li>
      <li><el-button size="small" type="primary" @click="onOrderOtherEdit" v-if="status.isEdit">添加</el-button></li>
    </ul>
    <el-table :data="formOrderBuy.orderOtherCosts" class="flexible-table" border stripe tooltip-effect>
      <el-table-column type="index" label="序号" align="center" width="60" />
      <el-table-column prop="costName" label="费用名称" show-overflow-tooltip align="center" />
      <el-table-column prop="costAmount" label="费用明细" show-overflow-tooltip align="center" />
      <el-table-column prop="note" label="备注" show-overflow-tooltip align="center" />
      <el-table-column label="操作" show-overflow-tooltip align="center">
        <template #default="scope">
          <z-button icon="delete" type="danger" size="small" title="删除" @click="onOtherDel(scope.row)"></z-button>
        </template>
      </el-table-column>
    </el-table>

    <ul class="flow-page-header">
      <li>附件信息</li>
      <li>
        <el-upload drag action="#" :before-upload="beforeUpload" :limit="1" :show-file-list="false"
          :http-request="upload">
          <el-text type="primary">上传文件</el-text>
        </el-upload>
      </li>
    </ul>
    <!-- <el-table :data="formOrderBuy.orderBuyProducts" class="flexible-table" border stripe tooltip-effect>
      <el-table-column type="index" label="序号" align="center" width="60" />
      <el-table-column
        v-for="(item, index) in columns.buyDetail.filter(r => r.show)"
        :width="item.width"
        :min-width="item.minWidth"
        :prop="item.id"
        :label="item.label"
        :key="item.id + index"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          <template v-if="item.id === 'operate'">
            <z-button icon="xiugai" size="small" title="编辑" @click="onEdit(scope.row)" v-if="purview(3)"></z-button>
            <z-button icon="delete" type="danger" size="small" title="删除" @click="onDel([scope.row.id])" v-if="purview(4)"></z-button>
          </template>
          <template v-else>
            {{ scope.row[item.id] }}
          </template>
        </template>
      </el-table-column>
    </el-table> -->

    <orderOtherCostEdit v-model="status.otherShow" @onSave="onOtherCallback" />
  </div>
</template>
<script setup>
import upload from '@/config/upload';
import { get, post } from '@/api/index';
import orderOtherCostEdit from './components/orderOtherCostEdit.vue';
import buyForm from './components/buyForm.vue';
import buyTable from './components/buyTable.vue';
let $message = inject('$message');

let route = useRoute();
let router = useRouter();
let urlParams = computed(() => route.query);

let columns = reactive({
  buy: [
    { label: '单据编号', id: 'serialNo', show: true, value: null, type: 'input', required: true },
    { label: '供应商', id: 'providerId', show: true, value: null, type: 'z-select', api: 'Provider/GetSelectPage', required: true },
    { label: '开单日期', id: 'initiateDate', show: true, value: null, type: 'date', required: true },
    { label: '截止日期', id: 'abortDate', show: true, value: null, type: 'date', required: true },
    { label: '负责人', id: 'officeId', show: true, value: null, type: 'z-select', required: true },
    { label: '联系人', id: 'contact', show: true, value: null, type: 'input' },
    { label: '联系人电话', id: 'contactPhone', show: true, value: null, type: 'input' },
    { label: '地址', id: 'address', show: true, value: null, type: 'input' },
    {
      label: '交易币别',
      id: 'currencyId',
      show: true,
      value: null,
      type: 'z-select',
      api: 'DictionaryValue/GetPage',
      apiParams: { dictionaryType: 2, dictionaryTypeId: -2 }
    },
    {
      label: '汇率',
      id: 'exchangeRate',
      show: true,
      value: 0,
      type: 'input'
    },
    { label: '含税', id: 'isTax', show: true, value: false, type: 'switch' },
    { label: '订单金额', id: 'totalAmount', show: true, value: 0, type: 'text' },
    { label: '备注', id: 'note', show: true, value: '', type: 'textarea', col: 12 }
  ],
  buyDetail: [
    { label: '图片', id: 'imagePath', show: true, width: 80 },
    { label: '产品类目', id: 'categoryName', show: true, minWidth: 120 },
    { label: '产品编号', id: 'productSerialNo', show: true, width: 150 },
    { label: '产品名称', id: 'productName', show: true, minWidth: 200 },
    { label: '规格', id: 'extraSpec', show: true, minWidth: 180 },
    { label: '类型', id: 'productTypeName', show: true, width: 100 },
    { label: '数量', id: 'number', show: true, width: 100 },
    { label: '单位', id: 'unit', show: true, width: 100 },
    { label: '单价', id: 'price', show: true, width: 100 },
    { label: '税率', id: 'taxRate', show: false, width: 150, required: true },
    { label: '税费', id: 'taxAmount', show: false, width: 100, required: true },
    { label: '金额', id: 'totalAmount', show: true, width: 100 },
    { label: '仓库', id: 'whInfoId', show: true, width: 150 },
    { label: '库位', id: 'whInfoStorageId', show: true, width: 150 },
    { label: '备注', id: 'note', show: true, minWidth: 150 }
  ]
});

let formOrderBuy = reactive({
  statusId: 0,
  isAutoSerialNo: false,
  templateProgressId: 0,
  providerId: undefined,
  contact: '',
  contactPhone: '',
  address: '',
  serialNo: '',
  officeId: undefined,
  initiateDate: new Date(),
  abortDate: '',
  note: '',
  isTax: false,
  currencyId: undefined,
  exchangeRate: undefined,
  totalNumber: undefined,
  taxAmount: undefined,
  totalAmount: undefined,
  orderBuyProducts: [],
  orderOtherCosts: [],
  orderAttachDatas: [],
  customSpecValueDic: []
});

let status = reactive({
  customObjectValues: [],
  otherShow: false,
  isEdit: false,
});
// 查询详情，新增的时候也会调用
let modelQuery = async id => {
  let { result } = await get('OrderBuy/GetModel', { id });

  formOrderBuy.statusId = result.statusId;

  // 处理基本信息字段，以及产品列表信息字段
  let { productColumnJson, columnJson } = result.columnSetting;
  columnJson = columnJson ? JSON.parse(columnJson) : [];
  // 基本信息处理
  columns.buy = columns.buy.map(r => {
    let obj = { ...columnJson.find(row => row.id === r.id), ...r };
    obj.value = id ? result[r.id] : r.value;
    // select 处理
    if (r.type === 'z-select' && obj.value) {
      let labelName = r.id.substr(0, r.id.length - 2) + 'Name';
      obj.options = [{ value: obj.value, label: result[labelName] }];
    }
    return obj;
  });
  productColumnJson = productColumnJson ? JSON.parse(productColumnJson) : [];
  columns.buyDetail = columns.buyDetail.map(r => {
    let row = { ...r, ...productColumnJson.find(row => row.id === r.id) };
    // 单独处理 税费 税率的问题
    if (['taxRate', 'taxAmount'].includes(row.id)) {
      row.show = isTax.value;
    }
    return row;
  });
  if (result.orderBuyProducts) {
    // 产品信息
    formOrderBuy.orderBuyProducts = result.orderBuyProducts.map(r => {
      return {
        ...r,
        ...{
          whInfoId: r.whInfoId || null,
          whInfoStorageId: r.whInfoStorageId || null,
          taxRate: r.taxRate || null
        }
      };
    });
  }
  status.customObjectValues = result.customObjectValues;
};
// 初始化
onActivated(async () => {
  status.isEdit = Number(urlParams.value.id) === 0;
  await modelQuery(Number(urlParams.value.id) || 0);
});
// 返回
let onBack = () => {
  router.go(-1);
};

let onRefresh = () => { };
let specRef = ref();
let buyFormRef = ref();
let buyTableRef = ref();
// 点击保存，先处理验证
let onSave = async () => {
  // 基本信息验证;
  let buyFormCheck = await buyFormRef.value.check();
  if (!buyFormCheck) return;
  // 自定义字段信息验证
  let customObjectValues = status.customObjectValues.length ? await specRef.value.check() : true;
  if (!customObjectValues) return;
  // 如果上面二个认证都过了。就看商品的验证
  let orderBuyProducts = await buyTableRef.value.check();
  if (!orderBuyProducts) return;
  buyFormCheck.currencyId = buyFormCheck.currencyId || 0;
  buyFormCheck.exchangeRate = buyFormCheck.exchangeRate || 0;
  let { result } = await post('OrderBuy/CreateOrUpdate', { id: urlParams.value.id, TemplateProgressId: 35, ...buyFormCheck, orderBuyProducts, customObjectValues });
  $message.success("保存成功");
  await modelQuery(result);
  urlParams.value.id = result;
  status.isEdit = false;
};

// 重置草稿
let onDreaf = async () => {
  let { result } = await get('OrderBuy/Reset', { id: urlParams.value.id });
  $message.success("重置成功");
  await modelQuery(result);
}

let onEdit = () => {
  status.isEdit = true;
}

let onSubmit = async () => {
  // 基本信息验证;
  let buyFormCheck = await buyFormRef.value.check();
  if (!buyFormCheck) return;
  // 自定义字段信息验证
  let customObjectValues = status.customObjectValues.length ? await specRef.value.check() : true;
  if (!customObjectValues) return;
  // 如果上面二个认证都过了。就看商品的验证
  let orderBuyProducts = await buyTableRef.value.check();
  if (!orderBuyProducts) return;
  buyFormCheck.currencyId = buyFormCheck.currencyId || 0;
  buyFormCheck.exchangeRate = buyFormCheck.exchangeRate || 0;
  let { result } = await post('OrderBuy/Submit', { id: urlParams.value.id, TemplateProgressId: 35, ...buyFormCheck, orderBuyProducts, customObjectValues });
  $message.success("提交成功");
  await modelQuery(result);
  urlParams.value.id = result;
  status.isEdit = false;
}

// 其他费用操作
const onOrderOtherEdit = () => {
  status.otherShow = true;
};

const onOtherCallback = val => {
  if (!formOrderBuy.orderOtherCosts) formOrderBuy.orderOtherCosts = [];
  if (val) formOrderBuy.orderOtherCosts.push({ ...{}, ...val });
  status.otherShow = false;
};

const onOtherDel = row => {
  formOrderBuy.orderOtherCosts = formOrderBuy.orderOtherCosts.filter(n => n.costName != row.costName && n.costAmount != row.costAmount);
};
// 基础信息展示
const buyFormColumn = computed(() => {
  return columns.buy.filter(r => r.show);
});
// 是否含税展示
const isTax = computed(() => {
  let row = columns.buy.find(r => r.id === 'isTax') || {};
  return row.value;
});
const beforeUpload = file => {
  if (file.size / 1024 > 20 * 1024) {
    this.$global.notify(`文件过大！不能超过${Number(20)}M ！`, true);
    return false;
  }
  return true;
};
</script>

<style lang="scss" scoped>
.orderBuyEdit {
  height: 100%;
  background-color: #fff;
  padding: 10px;
  overflow-x: hidden;
  overflow-y: auto;

  :deep(.date-picker) {
    width: 100%;

    .el-input__wrapper {
      width: 100%;
    }
  }

  .flow-page-header {
    margin-top: 20px;
    width: 100%;
    background-color: #d6f2f7;
    display: flex;
    justify-content: space-between;
    height: 36px;
    line-height: 36px;
    padding: 0px 10px;
  }

  .header-buttons {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
  }
}
</style>
